import threading
from random import randint
from threading import Thread
from time import sleep


class Account(object):
    def __init__(self, accountnumber, balance=100):
        self._accountnumber = accountnumber
        self._balance = balance
        self._lock = threading.Lock()

    @property
    def accountnumber(self):
        return self._accountnumber

    @accountnumber.setter
    def accountnumber(self, accountnumber):
        self._accountnumber = accountnumber

    @property
    def balance(self):
        return self._balance

    @balance.setter
    def balance(self, balance):
        self._balance = balance

    def transfer(self, amount):
        sleep(0.01)
        thread = threading.current_thread()
        if amount < self._balance:
            print("线程%s,扣费%d\n" % (thread.name, amount))
            self._balance -= amount
        else:
            print("线程%s,余额不足%d\n" % (thread.name, amount))

    ##加锁
    def transferLock(self, amount):
        self._lock.acquire()
        try:
            sleep(0.01)
            thread = threading.current_thread()
            if amount < self._balance:
                print("线程%s,扣费%d\n" % (thread.name, amount))
                self._balance -= amount
            else:
                print("线程%s,余额不足%d\n" % (thread.name, amount))
        finally:
            self._lock.release()


if __name__ == '__main__':
    threads = []
    account = Account("123456789", 100)
    print("交易前余额=%f" % account.balance)

    for x in range(10):
        #t = Thread(target=account.transfer, args=(randint(20, 30),))
        ##加锁处理并发
        t = Thread(target=account.transferLock, args=(randint(20, 30),))
        t.start()
        threads.append(t)

    ## balance是一个共享变量，多个线程一起扣费，线程不安全会扣成负数
    for thread in threads:
        thread.join()
    print("交易后余额=%f" % account.balance)
